package xiaolong.lian.web.interceptor;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import xiaolong.lian.util.Auth;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckLogged extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        String tel = "";
        String token = "";
        for(Cookie cookie : cookies){
            if(cookie.getName().equals("tel"))
                tel = cookie.getValue();
            else if(cookie.getName().equals("token"))
                token = cookie.getValue();
        }
        if(!Auth.isValidToken(tel, token)){
            JSONObject object = new JSONObject();
            object.put("msg", "认证信息已过期，请重新登录");
            response.setContentType("application/json; charset=utf-8");
            response.setStatus(401);
            response.getWriter().write(object.toJSONString());
            return false;
        }
        request.setAttribute("tel", tel);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        Auth.setPermissionUnchecked();
        super.postHandle(request, response, handler, modelAndView);
    }
}
